﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Tools.Log;
namespace Lion.WeiXin
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class PermissionFilterAttribute : ActionFilterAttribute,IExceptionFilter
    {

        static string _CURRENT_USER = "CurrentUser";
        static string _PERMISSION = "Permission";
        /// <summary>
        /// 执行action 方法之前执行的动作： 验证用户是否有权限执行当前请求
        /// </summary>
        /// <param name="actionContext"></param> 
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            
           // base.OnActionExecuting(filterContext);
            string controllerName = filterContext.RouteData.Values["controller"].ToString();
            string actionName = filterContext.RouteData.Values["action"].ToString();
            string Url = HttpContext.Current.Request.RawUrl;
            Url = HttpContext.Current.Server.UrlEncode(Url);
            string method = HttpContext.Current.Request.HttpMethod.ToUpper();
          
            ////1 未登陆用户 Cookie 验证法
            //if (!HttpContext.Current.User.Identity.IsAuthenticated)
            //{
            //    filterContext.Result = new RedirectResult("~/Welcome/Login?ReturnUrl=" + Url);
            //}
            //未登陆用户，Session 验证法
            if (HttpContext.Current.Session[_CURRENT_USER] == null || HttpContext.Current.Session[_PERMISSION]==null)
            {
                filterContext.Result = new RedirectResult("~/Welcome/Login?ReturnUrl=" + Url);
            }
            else
            {
                EmployeeModel model = (EmployeeModel)HttpContext.Current.Session[_CURRENT_USER];
                if (model.Role_ID != 1)
                {
                    //成功登陆后
                    //2 可加入账号单点登录验证
                    //3 验证是否多少天没修改密码
                    //4 当前用户是否具有访问权限
                    //检查用户可访问的权限
                    string requestUrl = string.Format(@"/{0}/{1}", controllerName, actionName);
                    if (CurrentUser.PermissionMenus.Where(n => n.Url.Contains(requestUrl)).Count() <= 0)
                    {
                        //无请求的权限
                        //JavaScriptResult jsResult = new JavaScriptResult();
                        //jsResult.Script = "alert('没有欲访问网页的权限，请与管理员联系！');history.go(-1);";
                        // filterContext.Result = jsResult;
                        //如果是get 方式，跳转到一个连接，如果是post 方式，返回json格式
                        if (method == "GET")
                        {
                            filterContext.Result = new RedirectResult("~/Welcome/Stopping?ReturnUrl=" + Url);
                        }
                        else if (method == "POST")
                        {
                            JsonResult json = new JsonResult();
                            json.Data = new { code = SaveStateEnum.NO.ToString(), msg = "您没有访问该网页的权限，请与管理员联系！" };
                            filterContext.Result = json;

                        }
                    }
                }
            }
        }

        public void OnException(ExceptionContext filterContext)
        {
            //获取异常信息，入库保存 
            Exception Error = filterContext.Exception;
            string Message = Error.Message;//错误信息 
            string Url = HttpContext.Current.Request.RawUrl;//错误发生地址 
            filterContext.ExceptionHandled = true;
            //记录错误文本日志
            LogHelper.Error(Error, "请求页面[{0}],发生异常", Url);
            filterContext.Result = new RedirectResult("/Shared/Error/");//跳转至错误提示页面 
        }
    }
}